<?php
declare(strict_types=1);

namespace app\adminapi\middleware;


use app\dm\exceptions\ExpireException;
use app\dm\services\InteriorCodeService;
use app\dm\traits\JwtAuthTrait;
use app\model\SysAdminModel;
use Closure;
use Exception;

/**
 * Token效验
 * Class AdminAuth
 *
 * @package app\http\middleware
 */
class AdminAuth
{
    use JwtAuthTrait;

    public function handle($request, Closure $next)
    {
        try {
            // 获取请求头Token
            $token = $this->getRequestToken($request);
            // 验证签名是否过期
            if (!$token || !$this->checkTokenFromCache($token)) {
                throw new ExpireException('签名过期');
            }
            // 拿到用户表对象
            $qx_admin_model = new SysAdminModel();
            // 对Token进行解析 返回用户对象和解析的Token
            $payload        = $this->parseToken($token, $qx_admin_model);
        } catch (Exception $e) {
            throw $e;
        }
        // 操作方法
        $action = $request->action();
        if ($action && strtolower('refreshToken') !== $action && $payload['payload']->scope === 'refresh') {
            throw new InvalidParamsException('token类型错误', InteriorCodeService::TOKEN_SCOPE_INVALID);
        }
        if (!in_array($payload['payload']->aud, config('domain.aud_domain'), true)) {
            throw new DomainNotAllowException();
        }
        // 注入admin信息（数组）
        $request->admin = $payload['obj'];
        return $next($request);
    }
}